import React, { forwardRef, useRef } from "react";
import { observer } from "mobx-react-lite";
import cn from "classnames";
import { useWindowClick } from "@/hooks/useWindowClick";

import cls from "./Dropdown.module.scss";

// Dropdown
type Props = {
  isOpen: boolean;
  close: () => void;
  children: React.ReactNode;
  fullWidth?: boolean;
  dropTop?: boolean;
  ownList?: boolean;
  className?: string;
  parentCls?: string;
};

export const Dropdown: React.FC<Props> = observer(
  ({
    isOpen,
    close,
    children,
    fullWidth,
    className,
    parentCls,
    dropTop,
    ownList,
  }) => {
    const rootRef = useRef<HTMLDivElement>(null);

    useWindowClick((e) => {
      const el = e.target as HTMLElement | null;
      const parentEl = parentCls ? el?.closest(`.${parentCls}`) : null;

      const clickedRoot = parentEl
        ? parentEl.querySelector(`.${cls.root}`)
        : null;
      const thisRoot = rootRef?.current;

      if ((!!clickedRoot && clickedRoot !== thisRoot) || !parentEl) {
        close();
      }
    });

    return (
      <div
        data-dropdown
        ref={rootRef}
        className={cn(
          cls.root,
          {
            [cls.root_open]: isOpen,
            [cls.root_fullwidth]: fullWidth,
            [cls.root_top]: !!dropTop,
          },
          className
        )}
      >
        {ownList ? children : <ul className={cls.list}>{children}</ul>}
      </div>
    );
  }
);

// Dropdown item
type ItemProps = {
  children: React.ReactNode;
  itemKey?: React.Key;
};

export const DropdownItem = forwardRef<HTMLLIElement, ItemProps>(
  ({ children, itemKey }, ref) => {
    return (
      <li className={cls.li} key={itemKey} ref={ref}>
        {children}
      </li>
    );
  }
);
